package util;

import java.util.List;
import java.util.Stack;

/**
 * 后缀表达式求解器
 * 1. 判断一个逆波兰式是否是合法
 * 2. 如果是合法的，则计算出该式的值
 * 3. 静态方法工厂 Math/Arrays/Collections
 */
public class Evaluator {


    public static final double ERROR = -1.0;

    private Evaluator() {
    }

    /**
     * 后缀表达式计算方法
     * 基于栈的操作
     *
     * @param exp
     * @return
     */
    public static Double eval(List<String> exp) {
        Stack<Double> stack = new Stack<>();
        try {
            for (String tok : exp) {
                if (tok.equals("+") || tok.equals("-") || tok.equals("*") || tok.equals("/")) {
                    Double b = stack.peek();
                    stack.pop();
                    Double a = stack.peek();
                    stack.pop();
                    Double c = 0.0;
                    switch (tok.charAt(0)) {
                        case '+':
                            c = a + b;
                            break;
                        case '-':
                            c = a - b;
                            break;
                        case '*':
                            c = a * b;
                            break;
                        case '/':
                            if (b == 0.0) return ERROR;
                            c = a / b;
                            break;
                        default:
                            break;
                    }
                    stack.push(c);
                } else {
                    stack.push(Double.valueOf(tok));
                }
            }
        } catch (Exception e) {
            return ERROR;
        }


        return stack.size() != 1 ? ERROR : stack.peek();
    }
}
